package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.BindMemberReq;
import com.ydkj.a37e_mall.Classes.Model.Request.BindOauthReq;
import com.ydkj.a37e_mall.Classes.Model.Request.GetCountOauthReq;
import com.ydkj.a37e_mall.Classes.Model.Request.UnBindOauthReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetCountOauthResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.DataCleanManager;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cz.msebera.android.httpclient.Header;

import static com.ydkj.a37e_mall.R.id.tv_cache_size;

/**
 * Created by Administrator on 2017/3/3.
 * 我的账号
 */

public class MyAccountActivity extends BaseActivity implements View.OnClickListener, PlatformActionListener {
    Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private ImageView img_back;
    private RelativeLayout rly_phonenum, rly_weixinnum, rly_qqnum, rly_sinanum;
    private TextView tv_phone_name, tv_weixin_name, tv_qq_name, tv_sina_name;
    private TextView tv_phone_binding, tv_weixin_binding, tv_qq_binding, tv_sina_binding;
    private List<GetCountOauthResp.ResultEntity.DataEntity> CountOauthlist;
    private Handler handler;

    private static final int MSG_SMSSDK_CALLBACK = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;
    private int type; //1为微信,2为微博,3为qq
    private String openId;
    private String name;
    private String icon;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_account);
        mActivity = this;
        init();
    }

    private void init() {
        myApplication = MyApplication.getInstance();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);

        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        rly_phonenum = (RelativeLayout) mActivity.findViewById(R.id.rly_phonenum);
        rly_weixinnum = (RelativeLayout) mActivity.findViewById(R.id.rly_weixinnum);
        rly_qqnum = (RelativeLayout) mActivity.findViewById(R.id.rly_qqnum);
        rly_sinanum = (RelativeLayout) mActivity.findViewById(R.id.rly_sinanum);

        tv_phone_name = (TextView) mActivity.findViewById(R.id.tv_phone_name);
        tv_weixin_name = (TextView) mActivity.findViewById(R.id.tv_weixin_name);
        tv_qq_name = (TextView) mActivity.findViewById(R.id.tv_qq_name);
        tv_sina_name = (TextView) mActivity.findViewById(R.id.tv_sina_name);
        tv_phone_binding = (TextView) mActivity.findViewById(R.id.tv_phone_binding);
        tv_weixin_binding = (TextView) mActivity.findViewById(R.id.tv_weixin_binding);
        tv_qq_binding = (TextView) mActivity.findViewById(R.id.tv_qq_binding);
        tv_sina_binding = (TextView) mActivity.findViewById(R.id.tv_sina_binding);

        CountOauthlist = new ArrayList<>();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_AUTH_CANCEL: {
                        Log.e("ssss", "取消授权");

                        //取消授权
                        Toast.makeText(mActivity, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case MSG_AUTH_ERROR: {
                        Log.e("ssss", "授权失败");

                        //授权失败
                        Toast.makeText(mActivity, R.string.auth_error, Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case MSG_AUTH_COMPLETE: {
                        Log.e("ssss", "授权成功");
                        //授权成功
                        Toast.makeText(mActivity, R.string.auth_complete, Toast.LENGTH_SHORT).show();
                        Object[] objs = (Object[]) msg.obj;
                        String platform = (String) objs[0];
                        HashMap<String, Object> res = (HashMap<String, Object>) objs[1];

                        Log.e("ssss", "platform==》" + platform);
                        if (platform.equals("QQ")) {
                            QQ qq = new QQ(mActivity);
                            openId = qq.getDb().getUserId();
                            icon = qq.getDb().getUserIcon();
                            name = qq.getDb().getUserName();
                            Log.e("ssss", "qqopenId==》" + openId);
                            Log.e("ssss", "qqopenicon==》" + icon);
                            Log.e("ssss", "qqopenname==》" + name);
                            BindOauth(openId, type + "", icon, name);
                        }
                        if (platform.equals("Wechat")) {
                            Wechat weixin = new Wechat(mActivity);

                            openId = weixin.getDb().getUserId();
                            icon = weixin.getDb().getUserIcon();
                            name = weixin.getDb().getUserName();
                            Log.e("ssss", "weixinqqopenId==》" + openId);
                            Log.e("ssss", "weixinqqopenicon==》" + icon);
                            Log.e("ssss", "weixinqqopenname==》" + name);
                            BindOauth(openId, type + "", icon, name);
                        }
                        if (platform.equals("SinaWeibo")) {
                            SinaWeibo sina = new SinaWeibo(mActivity);
                            openId = sina.getDb().getUserId();
                            icon = sina.getDb().getUserIcon();
                            name = sina.getDb().getUserName();
                            Log.e("ssss", "sinaqqopenId==》" + openId);
                            Log.e("ssss", "sinaqqopenicon==》" + icon);
                            Log.e("ssss", "sinaqqopenname==》" + name);
                            BindOauth(openId, type + "", icon, name);
                        }


                    }
                    break;
                    case MSG_SMSSDK_CALLBACK: {
//                if (msg.arg2 == SMSSDK.RESULT_ERROR) {
//                    Toast.makeText(mActivity, "操作失败", Toast.LENGTH_SHORT).show();
//                } else {
//                    switch (msg.arg1) {
//                        case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE: {
//                            if (msgLoginDlg != null && msgLoginDlg.isShowing()) {
//                                msgLoginDlg.dismiss();
//                            }
//                            Toast.makeText(mActivity, "提交验证码成功", Toast.LENGTH_SHORT).show();
//                            Message m = new Message();
//                            m.what = MSG_AUTH_COMPLETE;
//                            m.obj = new Object[]{"SMSSDK", (HashMap<String, Object>) msg.obj};
//                            handler.sendMessage(m);
//                        }
//                        break;
//                        case SMSSDK.EVENT_GET_VERIFICATION_CODE: {
//                            Toast.makeText(mActivity, "验证码已经发送", Toast.LENGTH_SHORT).show();
//                        }
//                        break;
//                    }
//                }
                    }
                    break;
                }
            }
        };


        rly_phonenum.setOnClickListener(this);
        rly_weixinnum.setOnClickListener(this);
        rly_qqnum.setOnClickListener(this);
        rly_sinanum.setOnClickListener(this);

        tv_phone_binding.setOnClickListener(this);
        tv_weixin_binding.setOnClickListener(this);
        tv_qq_binding.setOnClickListener(this);
        tv_sina_binding.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //解绑
            case R.id.rly_phonenum:

                break;
            case R.id.rly_weixinnum:
                initClearDialog("微信", "1");
                break;
            case R.id.rly_qqnum:
                initClearDialog("QQ", "3");
                break;
            case R.id.rly_sinanum:
                initClearDialog("微博", "2");
                break;


            //绑定
            case R.id.tv_phone_binding:
                startActivity(new Intent(mActivity, BindPhotoActivity.class));

                break;
            case R.id.tv_weixin_binding:
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);

                if (!wechat.isClientValid()) {
                    Toast.makeText(mActivity, "微信未安装,请先安装微信", Toast.LENGTH_LONG).show();
                    return;
                }
                type = 1;
                authorize(wechat);
                break;
            case R.id.tv_qq_binding:
                //QQ
                Platform qzone = ShareSDK.getPlatform(QQ.NAME);
                type = 3;
                authorize(qzone);
                break;
            case R.id.tv_sina_binding:
                //新浪微博
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                type = 2;
                authorize(sina);
                break;

        }
    }

    //获取我的账号绑定信息
    private void GetCountOauth() {
        if (myApplication.getDataEntity() == null) {
            CommonUtil.showToast(mActivity, "获取账号信息失败，请检查是否登录..");
            return;
        }

        CustomProgressDialog.createDialog(mActivity).show();
        final GetCountOauthReq req = new GetCountOauthReq();
        req.setUuid(myApplication.getDataEntity().getUuid());
        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Log.e("ssss", "我的账号==》" + req.getSecret());

        Log.e("ssss", "我的账号==》" + req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("ssss", "我的账号==>" + response);
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");

                if (errno.equals("000")) {


                    GetCountOauthResp resp = GsonImpl.get().toObject(response.toString(), GetCountOauthResp.class);
                    CountOauthlist.clear();
                    CountOauthlist.addAll(resp.getResult().getData());

                    tv_phone_name.setVisibility(View.GONE);
                    tv_phone_binding.setVisibility(View.VISIBLE);


                    if (myApplication.getDataEntity().getMobile().length() == 11) {
                        tv_phone_name.setText(myApplication.getDataEntity().getMobile());
                        tv_phone_name.setVisibility(View.VISIBLE);
                        tv_phone_binding.setVisibility(View.GONE);
                    }

                    tv_weixin_name.setVisibility(View.GONE);
                    tv_weixin_binding.setVisibility(View.VISIBLE);

                    tv_sina_name.setVisibility(View.GONE);
                    tv_sina_binding.setVisibility(View.VISIBLE);

                    tv_qq_name.setVisibility(View.GONE);
                    tv_qq_binding.setVisibility(View.VISIBLE);

                    for (int i = 0; i < CountOauthlist.size(); i++) {
                        Log.e("ssss", "第三方类型==>" + CountOauthlist.get(i).getO_type());
                        Log.e("ssss", "第三方名称==>" + CountOauthlist.get(i).getO_nickname());
                        if (CountOauthlist.get(i).getO_type().equals("1")) {
                            //微信
                            Log.e("ssss", "111");

                            tv_weixin_name.setVisibility(View.VISIBLE);
                            tv_weixin_binding.setVisibility(View.GONE);
                            rly_weixinnum.setVisibility(View.VISIBLE);
                            tv_weixin_name.setText(CountOauthlist.get(i).getO_nickname());

                        }


                        if (CountOauthlist.get(i).getO_type().equals("2")) {
                            //微博
                            Log.e("ssss", "3333");
                            tv_sina_name.setVisibility(View.VISIBLE);
                            tv_sina_binding.setVisibility(View.GONE);
                            rly_sinanum.setVisibility(View.VISIBLE);
                            tv_sina_name.setText(CountOauthlist.get(i).getO_nickname());
                        }


                        if (CountOauthlist.get(i).getO_type().equals("3")) {
                            //qq
                            Log.e("ssss", "555");
                            tv_qq_name.setVisibility(View.VISIBLE);
                            tv_qq_binding.setVisibility(View.GONE);
                            rly_qqnum.setVisibility(View.VISIBLE);
                            tv_qq_name.setText(CountOauthlist.get(i).getO_nickname());

                        }
                    }
                } else {
                    tv_phone_name.setVisibility(View.VISIBLE);
                    tv_phone_binding.setVisibility(View.GONE);

                    tv_weixin_name.setVisibility(View.GONE);
                    tv_weixin_binding.setVisibility(View.VISIBLE);

                    tv_qq_name.setVisibility(View.GONE);
                    tv_qq_binding.setVisibility(View.VISIBLE);

                    tv_sina_name.setVisibility(View.GONE);
                    tv_sina_binding.setVisibility(View.VISIBLE);

                    tv_phone_name.setText(myApplication.getDataEntity().getMobile());
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }


    //手机号码绑定第三方登录
    private void BindOauth(String openid, String type, String icon, String name) {
        CustomProgressDialog.createDialog(mActivity).show();
        BindOauthReq req = new BindOauthReq();
        req.setOpen_id(openid);
        req.setType(type);
        req.setAvatar(icon);
        req.setNickname(name);

        RequestParams params = new RequestParams();
//        params.put("uuid", myApplication.getDataEntity().getUuid());
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        AsyncHttpClient httpClient = new AsyncHttpClient();
        httpClient.put(Const.COMMON_ADDRESS + req.urlString() + myApplication.getDataEntity().getUuid(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");
                if (errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmag);
                    GetCountOauth();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }


    //解除绑定
    private void UnBindOauth(String type) {
        CustomProgressDialog.createDialog(mActivity).show();
        UnBindOauthReq req = new UnBindOauthReq();
        req.setType(type);
        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        AsyncHttpClient httpclient = new AsyncHttpClient();
        httpclient.put(Const.COMMON_ADDRESS + req.urlString() + myApplication.getDataEntity().getUuid(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");
                if (errno.equals("000")) {
                    CommonUtil.showToast(mActivity, errmag);
                    GetCountOauth();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }


    private void initClearDialog(String text, final String type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setMessage("是否解除" + text + "绑定");
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UnBindOauth(type);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    //执行授权,获取用户信息
    //文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
    private void authorize(Platform plat) {
//        CustomProgressDialog.createDialog(mActivity).show();
        if (plat == null) {
//            popupOthers();
            return;
        }

        Log.e("ssss", "第三方登录==》" + plat + "");
        plat.setPlatformActionListener(this);
        //关闭SSO授权
        plat.SSOSetting(true);
        plat.showUser(null);
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Log.e("ssss", "111111");
        Log.e("ssss", "platform===>" + platform);
        Log.e("ssss", "iiiii===>" + action);
        Log.e("ssss", "res===>" + res);
        if (action == Platform.ACTION_USER_INFOR) {
            Log.e("ssss", "hander");
            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = new Object[]{platform.getName(), res};
            handler.sendMessage(msg);
        }
    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        Log.e("ssss", "222222");

        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        t.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        Log.e("ssss", "33333");

        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("ssss", "onresume");
        if (myApplication.getDataEntity() != null) {
            GetCountOauth();
        }
    }
}
